<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <!-- 移除错误的 </el-form-item> -->
      <el-form-item label="设备编号" prop="deviceNumber">
        <el-input
          v-model="queryParams.deviceNumber"
          placeholder="请输入设备编号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="currentStatus">
        <el-select
          v-model="queryParams.currentStatus"
          placeholder="设备状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.equipment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equipment:camera:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:camera:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment:camera:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equipment:camera:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="设备编号" prop="deviceNumber" width="120" />
      <el-table-column label="监控视频" prop="videoPath" width="120">
        <template slot-scope="scope">
          <el-link type="primary" :href="scope.row.videoPath" target="_blank" v-if="scope.row.videoPath">
            查看视频
          </el-link>
          <span v-else>无视频</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.equipment_status" :value="scope.row.currentStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="绑定冷库(冷库名)" align="center" width="150">
        <template slot-scope="scope">
          <el-button v-if="!scope.row.lgSubCold" @click="handleUpdate(scope.row)" size="mini" type="primary" v-hasPermi="['equipment:camera:updateVehicle']">绑定冷库</el-button>
          <el-tag v-if="scope.row.lgSubCold" type="success">{{ scope.row.lgSubCold.subName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="购买时间" align="center" prop="purchaseDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:camera:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:camera:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input v-model="form.deviceNumber" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="购买时间" prop="purchaseDate">
          <el-date-picker
            v-model="form.purchaseDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" 
            placeholder="请选择购买时间"
          ></el-date-picker>
        </el-form-item>
        <!-- 新增监控视频路径 -->
        <el-form-item label="监控视频路径" prop="videoPath">
          <el-input v-model="form.videoPath" placeholder="请输入监控视频路径" />
        </el-form-item>
        <el-form-item label="状态" prop="currentStatus">
          <el-select
            v-model="form.currentStatus"
            placeholder="设备状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.equipment_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定冷库">
          <el-button
            v-if="form.id && (form.coldStorageId != 0 && form.coldStorageId != undefined)"
            @click="handleCancelBound(form.id)"
            size="mini"
            type="primary"
            v-hasPermi="['equipment:camera:delBound']"
          >取消绑定</el-button>
          <Index v-if="(!form.id || (form.coldStorageId == 0 || form.coldStorageId == undefined))" :cid="cid" @close="handleCloseDialog"  @selected="handleSmallColdSelected"></Index>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCamera,
  getCamera,
  updateCamera,
  addCamera,
  delCamera,
  delBound
} from "@/api/equipment/camera";
import Index from '@/views/equipment/camera/smallCold/index.vue'
import CameraVideo from '@/views/equipment/camera/cameravideo/index.vue'
export default {
  components: {
    Index,
    CameraVideo
  },
  name: "Role",
  dicts: ['equipment_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      cid: undefined,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      currentStatus: 1,
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceNumber: undefined,
        currentStatus: undefined
      },
      // 表单参数
      form: {
        purchaseDate: null,
        videoPath: '' // 新增视频路径字段
      },
      rules: {
        deviceNumber: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ],
        videoPath: [
          { required: true, message: "监控视频路径不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      // 假设 addDateRange 方法用于处理日期范围，这里简单返回原参数
      const queryParamsWithDate = this.addDateRange
        ? this.addDateRange(this.queryParams, this.dateRange)
        : this.queryParams;
      listCamera(queryParamsWithDate).then(response => {
        console.log('Response data:', response.rows); // 打印返回的数据
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
        this.menuNodeAll = false,
        this.deptExpand = true,
        this.deptNodeAll = false,
        this.form = {
          roleId: undefined,
          orderNumber: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 选择车辆后关闭弹窗 */
    handleCloseDialog() {
      this.open = false; // 关闭弹窗
      this.getList();    // 可选：刷新数据
    },
    // 处理车辆选择
    handleSmallColdSelected(subId) {
      // 更新表单中的冷库绑定信息
      console.log('Selected subId:', subId);
      this.form.coldStorageId = subId;
      // 或者直接刷新列表数据
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加角色";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const cameraId = row.id || this.ids;
      getCamera(cameraId).then(response => {
        this.form = response.data;
        this.cid = response.data.id;
        this.form.currentStatus = this.form.currentStatus.toString();
        // 确保购买时间格式正确，修改为精确到时分秒的格式
        this.form.purchaseDate = this.parseTime(response.data.purchaseDate, '{y}-{m}-{d} {h}:{i}:{s}');
        // 确保 form.id 和 form.coldStorageId 正确设置
        console.log('form.id:', response);
        this.form.id = response.data.id;
        this.form.coldStorageId = response.data.coldStorageId; // 添加这一行
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if(value !== '2') {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            this.form.updateBy = this.$store.getters.name;
            // 打印 form 对象，确认 coldStorageId 是否存在
            console.log('提交的表单数据:', this.form);
            updateCamera(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createBy = this.$store.getters.name;
            // 打印 form 对象，确认 coldStorageId 是否存在
            console.log('提交的表单数据:', this.form);
            addCamera(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 取消绑定 */
    handleCancelBound(id) {
      this.$modal.confirm("确认要取消该绑定？").then(() => { // 改用箭头函数保持this指向
        return delBound({ id: id }); // 确保参数结构匹配接口要求
      }).then(() => {
        this.$modal.msgSuccess("解绑成功");
        this.open = false;  // 关闭弹窗
        this.getList();     // 重新加载数据
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cameraIds = row.id || this.ids;
      this.$modal.confirm(`是否确认删除 id 为 "${cameraIds}" 的数据项？`).then(() => { // 使用箭头函数
        return delCamera(cameraIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 假设 download 方法用于下载文件，这里简单给出提示
      if (!this.download) {
        console.error('download 方法未定义');
        return;
      }
      this.download('equipment/camera/export', {
        ...this.queryParams
      }, `GPSCamera_${new Date().getTime()}.xlsx`);
    },
    // 补充 addDateRange 方法（示例）
    addDateRange(params, dateRange) {
      if (dateRange && dateRange.length === 2) {
        params.startDate = dateRange[0];
        params.endDate = dateRange[1];
      }
      return params;
    },
    // 补充 download 方法（示例）
    download(url, params, filename) {
      // 这里可以实现具体的下载逻辑
      console.log('开始下载', url, params, filename);
    }
  }
};
</script>

<!-- 视频弹窗 -->
<el-dialog
  title="监控视频"
  :visible.sync="videoDialogVisible"
  width="70%"
  append-to-body
>
  <CameraVideo :videoUrl="currentVideoUrl" />
</el-dialog>
